# YS
# 2022/8/8 19:34
from datetime import datetime  # std library
import time  # std library
import pyvisa  # https://pyvisa.readthedocs.io/


timenow = datetime.now()
print(datetime.now(), '测量开始')
# Replace string with your instrument's VISA Resource Address
visaRsrcAddr = "USB0::0x0699::0x0522::C014382::INSTR"

rm = pyvisa.ResourceManager()
scope = rm.open_resource(visaRsrcAddr)
print(datetime.now(), '示波器型号及固件信息：', scope.query('*IDN?'), end='')  # Print instrument id to console window

"""
MEASUrement:MEAS<x>:TYPe
{ACCOMMONMODE|ACRMS|AMPlITUDE|AREA|BASE|BITAMPLITUDE|BITHIGH|
BITLOW|BURSTWIDTH|COMMONMODE|DATARATE|DCD|DDJ|DELAY|
DJ|DJDIRAC|EYEHIGH|EYELOW|FALLSLEWRATE|FALLTIME|FREQUENCY|
F2|F4|F8|HIGH|HEIGHT|HEIGHTBER|HIGHTIME|HOLD|JITTERSUMMARY|
J2|J9|LOW|LOWTIME|MAXIMUM|MEAN|MINIMUM|NDUtY|NPERIOD|NPJ|
NOVERSHOOT|NWIDTH|PDUTTY|PERIOD|PHASE|PHASENOISE|PJ|PK2Pk|
POVERSHOOT|PWIDTH|QFACTOR|RISESLEWRATE|RISETIME|RJ|RJDIRAC|
RMS|SRJ|SSCFREQDEV|SSCMODRATE|SETUP|
SKEW|TIE|TIMEOUTSIDELEVEL|TJBER|TNTRATIO|TOP|UNITINTERVAL|
VDIFFXOVR|WIDTH|WIDTHBER}
MEASUrement:MEAS<x>:TYPe
"""
# print(timenow,'示波器重置')
# scope.write('*RST') # reset
print(datetime.now(), '打开ch1')
scope.write('DISplay:WAVEView1:CH1:STATE ON')
print(datetime.now(), '打开ch2')
scope.write('DISplay:WAVEView1:CH2:STATE ON')
time.sleep(1)
# print(datetime.now(), '自动设置')
# scope.write('AUTOSET EXECUTE')
# print(datetime.now(),'操作结果：')
# time.sleep(1)
# scope.query('*OPC?')

# Set up conditional acquisition #
scope.write(f':ACQUIRE:STATE OFF;')
# scope.write(f':DISPLAY:WAVEVIEW1:CH{ch}:STATE 1;')
scope.write(f':HORIZONTAL:RECORDLENGTH 1000;')
scope.write(f':ACQUIRE:MODE SAMPLE;')
scope.write(f':ACQUIRE:STOPAFTER SEQUENCE;')
# scope.write('DISplay:WAVEView1:CH3:STATE OFF')
# scope.write('DISplay:WAVEView1:CH4:STATE OFF')
scope.write('HORIZONTAL:SAMPLERATE 25E9')
scope.write(':MEASUrement:GATing SCREEN;')
#  Acquire waveform data #
scope.write(':ACQUIRE:STATE ON;')
# scope.write('acquire:state 1')
# scope.write('MEASU:MEAS1:SOU CH1')
# scope.write('MEASU:MEAS2:SOU CH1')
# scope.write('MEASU:MEAS3:SOU CH1')

# scope.write('MEASUrement:MEAS1:TYPe FREQUENCY')
# print('FRE ? ',(scope.query('MEASU:MEAS1:VAL?')))
#
# scope.write('MEASUrement:MEAS2:TYPe AMPlITUDE')
# print('AMP ? ',(scope.query('MEASU:MEAS2:VAL?')))
#
# scope.write('MEASUrement:MEAS3:TYPe FALLTIME')
# print('FALL ? ',(scope.query('MEASU:MEAS3:VAL?')))
#
# print(scope.write('MEASUrement:MEAS1:RESUlts:CURRentacq:MEAN?'))


"""
For example, a typical application might involve acquiring a single-sequence
waveform and then taking a measurement on the acquired waveform. You could
use the following command sequence to do this:
/** Set up conditional acquisition **/
ACQUIRE:STATE OFF
DISPLAY:WAVEVIEW1:CH1:STATE 1
HORIZONTAL:RECORDLENGTH 1000
ACQUIRE:MODE SAMPLE
ACQUIRE:STOPAFTER SEQUENCE
/** Acquire waveform data **/
ACQUIRE:STATE ON
/** Set up the measurement parameters **/
MEASUREMENT:MEAS1:TYPE AMPLITUDE
MEASUREMENT:MEAS1:SOURCE CH1
/** Take amplitude measurement **/
MEASUREMENT:MEAS1:RESUlts:CURRentacq:MEAN?
"""


def save_png():
    scope.write('SAVE:IMAGe \"C:/Temp.png\"')
    print(datetime.now(),'处理结果：',scope.query('*OPC?'),end='')
    dt = datetime.now()
    fileName = dt.strftime("MSO5_%Y%m%d_%H%M%S.png")
    scope.write('FILESystem:READFile \"C:/Temp.png\"')
    imgData = scope.read_raw(1024 * 1024)
    file = open(fileName, "wb")
    file.write(imgData)
    file.close()
    scope.write('FILESystem:DELEte \"C:/Temp.png\"')
    scope.close()
    rm.close()
    print(datetime.now(), '图片保存完毕', fileName, end='')


def fetch_vpp(num, ch):
    scope.write(f':MEASUrement:MEAS{num}:TYPe PK2Pk;')
    scope.write(f':MEASUrement:MEAS{num}:SOUrce1 CH{ch};')
    # scope.query('*OPC?')
    time.sleep(0.1)
    vpp = scope.query(':MEASUrement:MEAS%d:RESUlts:CURRentacq:MEAN?;' % num)
    return vpp


def fetch_fre(num, ch):
    scope.write(f':MEASUrement:MEAS{num}:TYPe FREQUENCY;')
    scope.write(f':MEASUrement:MEAS{num}:SOUrce1 CH{ch};')
    # scope.query('*OPC?')
    time.sleep(0.1)
    fre = scope.query(':MEASUrement:MEAS%d:RESUlts:CURRentacq:MEAN?;' % num)
    return fre



def fetch_risetime(num, ch):
    scope.write(f':MEASUrement:MEAS{num}:TYPe RISETIME;')
    scope.write(f':MEASUrement:MEAS{num}:SOUrce1 CH{ch};')
    # scope.query('*OPC?')
    time.sleep(0.1)
    risetime = scope.query(':MEASUrement:MEAS%d:RESUlts:CURRentacq:MEAN?;' % num)
    return risetime


def fetch_falltime(num, ch):
    scope.write(f':MEASUrement:MEAS{num}:TYPe FALLTIME;')
    scope.write(f':MEASUrement:MEAS{num}:SOUrce1 CH{ch};')
    # scope.query('*OPC?')
    time.sleep(0.1)
    falltime = scope.query(':MEASUrement:MEAS%d:RESUlts:CURRentacq:MEAN?;' % num)
    return falltime

try:
    print(datetime.now(), '测量等待')
    print(datetime.now(), 'ch1峰峰值(V)：：', fetch_vpp(1, 1), end='')
    print(datetime.now(), 'ch1 FRE(Hz)：', fetch_fre(2, 1), end='')
    print(datetime.now(), 'ch1上升时间(ns)：', fetch_risetime(3, 1), end='')
    print(datetime.now(), 'ch1下降时间(ns)：', fetch_falltime(4, 1), end='')
    save_png()
    print(datetime.now(), '测量结束',end='')
except pyvisa.errors.VisaIOError:
    print(datetime.now(), '上述测量异常，请检查治具连接及通道状态', end='')
